package dao;


import util.DatabaseUtil;

import java.sql.*;

/**
 * 工具类
 * 执行数据库  增删改查的 工具类
 */
public class BaseDao {


     private Connection conn;


     public BaseDao(Connection conn){
          this.conn = conn;
     }
     /**
      * 增删改操作
      * */
     protected int executeUpdate(String sql,Object... params)
     {
          int result=0;
          PreparedStatement pstmt=null;
          try
          {
               //conn=this.getConnection();
               pstmt=conn.prepareStatement(sql);
               for (int i=0;i<params.length;i++)
               {
                    pstmt.setObject(i+1,params[i]);
               }
               result=pstmt.executeUpdate();
          }catch (SQLException e)
          {
               e.printStackTrace();
          }
          finally {
               //性能优化
               DatabaseUtil.close(null,pstmt,null);
          }
          return  result;
     }
     /**
      * 查询
      */
     protected  ResultSet executeQuery(String sql,Object... params)
     {
          PreparedStatement pstmt=null;
          ResultSet rs=null;
          try {
            //   conn=this.getConnection();
               pstmt=conn.prepareStatement(sql);
               for (int i=0;i<params.length;i++)
               {
                    pstmt.setObject(i+1,params[i]);
               }
               rs = pstmt.executeQuery();
          }catch (SQLException e)
          {
               e.printStackTrace();
          }
          return  rs;
     }
}
